

package examples.basic;

import commandz.cli.*;
import commandz.var.*;
import java.util.ArrayList;
import java.util.Collection;


/**
 *  Example of a Command-implementation which interacts with the
 *  Interpreter itself.
 */
public class HelpCommand implements Command
{
    private final String COMMAND_NAME = "help";
    private final String COMMAND_DESCRIPTION = "Provides information about a particular command.";

    protected Interpreter interpreter;
    protected VariableString topic;


    /**
     *  Initializes a new HelpCommand for use with the given Interpreter.
     *
     *  @param interpreter The interpreter to use.
     */
    public HelpCommand(final Interpreter interpreter)
    {
        this.interpreter = interpreter;
        this.topic = new VariableString();
    }


    /**
     *  Returns the name of this Command.
     *
     *  @see Command
     */
    public String getName()
    {
        return this.COMMAND_NAME;
    }


    /**
     *  Returns a brief description of this Command.
     *
     *  @see Command
     */
    public String getDescription()
    {
        return this.COMMAND_DESCRIPTION;
    }


    /**
     *  Publishes the topic-parameter.
     */
    public void publishParameters(Collection<Parameter> params)
    {
        params.add(new Parameter(this.topic, "topic",
                    "The name of a specific command to get information about."));
    }


    /**
     *  Executes this Command.
     *
     *  @see Command
     */
    public void execute()
    {
        String what = this.topic.getValue();
        Command cmd = this.interpreter.lookup(what);

        if (cmd == null)  // non-existing?
        {
            System.out.println("There is no help available for unknown " +
                               "command \"" + what + "\";\nUse the 'list' " +
                               "command to list all available commands.");
            return;
        }

        System.out.printf("\nCommand:\n\n\t%s - %s\n\nSynopsis:\n\n\t%s",
                    cmd.getName(), cmd.getDescription(), cmd.getName());

        Collection<Parameter> params = new ArrayList<Parameter>();
        cmd.publishParameters(params);

        if (params.isEmpty())
        {
            System.out.println('\n');
            return;
        }

        for (Parameter p : params)
            System.out.printf(" <%s>", p.getName());

        System.out.println("\n\nWhere:\n");

        for (Parameter p : params)
            System.out.printf("\t%s (%s) = %s\n", p.getName(),
                              p.getVariable().getTypeName(),
                              p.getDescription());

        System.out.println();
    }
}
